<?php

namespace library;
/**
 * Class Cast
 * 
 * @author raoyc <raoyc2009@gmaill.com>
 * @link   https://raoyc.com
 * @date   2017-08-18
 */
class Cast
{

    /**
     * 转换数据结果输出
     * 
     * @param  mixed $result 一般为 DB 查询结果（集）
     * @param  array $cast 字段转换的数组 示例 ['ui_id' => 'uid']
     * @param  string $replace 待替换前缀字段，多条前缀替换以 逗号 (,) 分隔 如 'ua_,ui_'
     * @param  array $exceptFields 排除不展示的字段数组
     * @return array
     */
    public static function castResult($result, array $cast = [], string $replace = '', array $exceptFields = [])
    {
        $_data = [];
        if(is_array($result) && is_numeric(implode('', array_keys($result))))
        {
            foreach ($result as $collection) {
                $_data[] = self::castResult($collection, $cast, $replace, $exceptFields);
            }
            return $_data;
        }
        if(is_array($result) && !is_numeric(implode('', array_keys($result)))) $result = json_decode(json_encode($result));
        // 默认排除不展示的字段
        $_defaultExceptFields = ['deleted_at', 'delete_flag', 'memo', 'password'];
        $exceptFields = array_merge($_defaultExceptFields, $exceptFields);
        if (is_object($result)) {
            foreach ($result as $k => $v) {
                if (array_key_exists($k, $cast)) {
                    $k = $cast[$k];
                }
                $replaceArr = explode(',', $replace);
                $k = str_replace($replaceArr, '', $k);
                if (!in_array($k, $exceptFields)) {
                    $_data[$k] = $v;
                }
            }
        }
        return $_data;
    }

}
